package iconcurrent;

import java.util.concurrent.*;

/**
 * 指令重排->带来的问题
 * @author or2
 * @date 2021/8/6 17:07
 */
public class OutOfOrderDemo {

    private static int a = 0, b = 0;
    private static int x = 0, y = 0;

    private static final CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Void> runnable = () -> {
            countDownLatch.await();
            a = 1;
//            延缓操作, cpu更容易切换时间片
            for (int i = 0; i < 10; i++) ;
            x = b;
            return null;
        };

        Callable<Void> runnable2 = () -> {
            countDownLatch.await();
            b = 1;
            for (int i = 0; i < 10; i++) ;
            y = a;
            return null;
        };
        //按照上面运行顺序, 不会出现 x = 0; 同时 y = 0

        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        int num = 0;
        do {
            x = y = a = b = 0;
            Future<Void> submit1 = threadPoolExecutor.submit(runnable);
            Future<Void> submit2 = threadPoolExecutor.submit(runnable2);
            countDownLatch.countDown();
            submit1.get();
            submit2.get();
            num++;
            System.out.println("num: " + num + "\tx = " + x + "\ty = " + y);
        } while (!(x == 0 && y == 0));

        threadPoolExecutor.shutdown();
    }
}
